/*Home Automation Control System (HACS version 0.1)

  Name: Colin Lobo
  Email: lobocjd@gmail.com
  Web: www.cas.mcmaster.ca/~lobocj
  
  Purpose:
  This program was designed as part of a personal project on
  home automation (http://en.wikipedia.org/wiki/Home_automation).
  
  Program Description:
  This program currently toggles an LED attached to an Arduino
  according to commands recieved from a computer attached via USB. 
  
  Notes:
  This program was uploaded onto an Arduino UNO Rev 2 board using the 
  Arduino 1.0.1 IDE. Note using a version <1.0 may cause the program
  to function incorrectly.
  
  Required Files:
    HACS.ino
*/    

//Initial packet is two bytes. one byte for header and another for data
char header = '0';
char data = '0';

void setup() {
  //set up serial and set pin 13 for output. most newer Arduino boards already have an led attached to pin 13.
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  //check if there is anything in the serial buffer
  if (Serial.available() > 0) {
    //check if there are exactly two bytes in the buffer
    if (Serial.available() == 2){
      //read the available bytes and store them
      header = Serial.read();
      data = Serial.read();
    }
  }
  
  //toggle the led according to the state of data (ie. data = '1' ON, data != '1' OFF)
  if (data == '1')
    digitalWrite(13, HIGH);
  else
    digitalWrite(13, LOW);
}
